﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;

namespace UserRedirect.Redirect_User_Web_Part
{
    [ToolboxItemAttribute(false)]
    public class Redirect_User_Web_Part : WebPart
    {
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            try
            {
                // Get the Site
                using (SPSite site = new SPSite(SPContext.Current.Site.ID))
                {
                    // Get the web
                    using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                    {
                        // Get Redirect User List
                        SPList list = web.Lists["Redirect Users"];

                        // Get List Items
                        SPListItemCollection listitems = list.Items;

                        // Loop through the list items
                        foreach (SPListItem listitem in listitems)
                        {
                            // Get a instance of the group
                            string SharePointGroup = listitem[new Guid("{04DC682E-F36D-48D3-A958-0FF699921F7F}")].ToString();
                            SPGroup Group = web.Groups[SharePointGroup];

                            // Check if user is in the group
                            if (Group.ContainsCurrentUser)
                            {
                                // Get the redirection URL
                                string LandingPage = listitem[new Guid("{5F86CF95-31A3-48FE-83AD-F74D26C514C5}")].ToString();

                                // Redirect the User
                                SPUtility.Redirect(LandingPage, SPRedirectFlags.Default, HttpContext.Current);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("InfoSystems", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, ex.Message, ex.StackTrace);
            }
        }
    }
}
